//https://mock.apipark.cn/m1/4727578-4380072-default 配件axios的基地址
axios.defaults.baseURL = "https://mock.apipark.cn/m1/4727442-4379935-default"

function showToast(msg) {
    const toastDom = document.querySelector(".my-toast");
    // 实例化toast组件
    const toast = new bootstrap.Toast(toastDom);// 修改提示
    document.querySelector(".toast-body").innerHTML = msg
    toast.show();
}
function renderUsername() {
    const username = localStorage.getItem("username");
    document.querySelector(".username").innerHTML = username
}
// 非法校验
function checkLogin() {
    // 判断token是否存在
    const token = localStorage.getItem("token");
    if (token == null) {
        showToast("你怎么进来的!登陆去!")
        setTimeout(() => {
            location.href = "./login.html"
        }, 1500)
    }
}

function registerLogout(){
    document.querySelector("#logout").addEventListener("click", () => {
        localStorage.removeItem("username")
        localStorage.removeItem("token")
        location.href = "./login.html"})
}
 
axios.interceptors.request.use(config =>{
    const token= localStorage.getItem("token")
    if(token){
    config.headers['Authorization']= token
    }
    return config},(error)=>{
    // 请求错误
    return Promise.reject(error)})

//响应拦截器
    axios,interceptors.response.use(response =>{
        //数据拆包
        return response.data },
        function(error){
        // 登录状态过期
        if(error.response.status === 401){
            localStorage.removeItem("token")
            localStorage,removeItem("username")
        showToast("登陆已过期,重新等了!")
        setTimeout(()=>{location.href ="/login.html"}
        ,1500)
        
        }
        return Promise.reject(error)
    })